/**
    @author: ChenLin
    @date: 2022/11/11
**/

package api

import (
	handler "../handler"
	service "../service"
	"encoding/json"
	"flamingo/base"
	"fmt"
	"io"
	"io/fs"
	"io/ioutil"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"
)

var Root string = "/tmp"
var VideoDir string = Root + "/video/"
var ImageDir string = Root + "/image/"
var Upload string = Root + "/upload/"

type HttpVideoServer struct {
	HttpVideoService *service.HttpVideoProcessService
	port             string
}

func NewHttpVideoServer(ch chan handler.VideoProcess, port string) *HttpVideoServer {
	var httpvideoServer = &HttpVideoServer{}
	httpvideoServer.HttpVideoService = service.NewHttpVideoProcessService(ch)
	httpvideoServer.port = port
	return httpvideoServer
}

func (self *HttpVideoServer) SetMysqlInfo(info base.MysqlInfo) {
	self.HttpVideoService.Mysql.SetMysqlInfo(info)
	self.HttpVideoService.Mysql.Init()
}

func (self *HttpVideoServer) SetDFS(appId string, appSecret string, hostUpload string, hostUpdate string, hostCheck string, hostCheckUrl string) {
	self.HttpVideoService.FlamingoDFS.Init(appId, appSecret, hostUpload, hostUpdate, hostCheck, hostCheckUrl)
}

func (self *HttpVideoServer) Init() {

	/*todo 上传链接压缩视频*/
	http.HandleFunc("/downloadVideoByUrl", self.downloadVideoByUrl)
	/*todo 上传文件压缩视频*/
	http.HandleFunc("/downloadVideoByFile", self.downloadVideoByFile)
	/*todo 分片上传文件压缩视频*/
	http.HandleFunc("/downloadVideoBySlice", self.downloadVideoBySlice)
	/*todo 上传字节流压缩视频 Content-Type:binary/octet-stream*/
	http.HandleFunc("/downloadVideoByBytes", self.downloadVideoByBytes)

	/*todo 上传链接返回截图地址*/
	http.HandleFunc("/getPictureOfVideoByUrl", self.getPictureOfVideoByUrl)
	/*todo 上传链接返回截图地址*/
	http.HandleFunc("/getPictureOfVideoByFile", self.getPictureOfVideoByFile)
	/*todo 上传字节流返回截图地址*/
	http.HandleFunc("/getPictureOfVideoByBytes", self.getPictureOfVideoByBytes)

	/*todo 添加url任务*/
	http.HandleFunc("/addTaskDownloadVideoByUrl", self.addTaskDownloadVideoByUrl)
	/*todo 添加file任务*/
	http.HandleFunc("/addTaskDownloadVideoByFile", self.addTaskDownloadVideoByFile)
	/*todo 添加bytes任务*/
	http.HandleFunc("/addTaskDownloadVideoByBytes", self.addTaskDownloadVideoByBytes)

	/*todo 查看分片文件状态*/
	http.HandleFunc("/CheckUploadChunk", self.CheckChunk)

	s := &http.Server{
		Addr:           ":" + self.port,
		ReadTimeout:    3 * 60 * time.Second,
		WriteTimeout:   3 * 60 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Println("listenAndServe: [ok]")
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal("listenAndServe: ", err)
	}
}

/**
 * @Author ChenLin
 * @Description //TODO 上传链接压缩视频不添加进任务（需要http长时间等待）
 * @Date 10:27 2022/11/11
 **/

func (self *HttpVideoServer) downloadVideoByUrl(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	w.Header().Set("Content-Type", "application/json")
	log.Println("pasteForm", req.PostForm, req.Form)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	url := req.Form["url"]
	result := handler.VideoProcess{}
	if len(url) < 1 {
		self.JsonResponse(w, 401, "url参数未传递", result)
		return
	}
	result.Url = url[0]
	videoUrl, err := self.HttpVideoService.DownloadVideo(url[0], VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil || videoUrl == "" {
		log.Println(err)
		_, err := self.HttpVideoService.InsertAndSetStatus(11, result) //11视频下载失败
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(1, result) //1视频已下载
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 22, result) //22视频截图失败
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 2, result) //2视频已截图
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 33, result) //33视频截图上传dfs失败
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 3, result) //3视频截图已上传dfs
	compressUrl, err := self.HttpVideoService.VideoCompress(videoUrl, VideoDir)
	result.CompressUrl = compressUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 44, result) //44视频压缩失败
		self.JsonResponse(w, 405, "视频压缩失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 4, result) //4视频已压缩
	dfsVideo, err := self.HttpVideoService.UploadVideoToDFS(compressUrl, compressUrl)
	result.VideoUrl = dfsVideo.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 55, result) //55压缩视频上传dfs失败
		self.JsonResponse(w, 406, "视频上传失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 5, result) //5压缩视频已上传dfs
	response := handler.ParseResponse(200, "视频压缩成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	//w.Write(jsonData)
	io.WriteString(w, string(jsonData))
	//marshal, err := json.Marshal(rep)
	//io.WriteString(w, string(marshal))
}

/**
 * @Author ChenLin
 * @Description //TODO 上传文件压缩视频
 * @Date 10:29 2022/11/11
 **/

func (self *HttpVideoServer) downloadVideoByFile(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	file, _, err := req.FormFile("video")
	defer file.Close()
	if err != nil {
		self.JsonResponse(w, 400, "文件传输失败", result)
		return
	}
	videoUrl, err := self.HttpVideoService.DownloadVideoByFile(file, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		_, err := self.HttpVideoService.InsertAndSetStatus(11, result) //11视频下载失败
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(1, result) //1视频已下载
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 22, result) //22视频截图失败
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 2, result) //2视频已截图
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 33, result) //33视频截图上传dfs失败
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 3, result) //3视频截图已上传dfs
	compressUrl, err := self.HttpVideoService.VideoCompress(videoUrl, VideoDir)
	result.CompressUrl = compressUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 44, result) //44视频压缩失败
		self.JsonResponse(w, 405, "视频压缩失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 4, result) //4视频已压缩
	dfsVideo, err := self.HttpVideoService.UploadVideoToDFS(compressUrl, compressUrl)
	result.VideoUrl = dfsVideo.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 55, result) //55压缩视频上传dfs失败
		self.JsonResponse(w, 406, "视频上传失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 5, result) //5压缩视频已上传dfs
	response := handler.ParseResponse(200, "视频压缩成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	//w.Write(jsonData)
	io.WriteString(w, string(jsonData))
}

func (self *HttpVideoServer) downloadVideoBySlice(w http.ResponseWriter, req *http.Request) {

}

func (self *HttpVideoServer) downloadVideoByBytes(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	videoUrl, err := self.HttpVideoService.DownloadVideoByBytes(req.Body, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		_, err := self.HttpVideoService.InsertAndSetStatus(11, result) //11视频下载失败
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(1, result) //1视频已下载
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 22, result) //22视频截图失败
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 2, result) //2视频已截图
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 33, result) //33视频截图上传dfs失败
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 3, result) //3视频截图已上传dfs
	compressUrl, err := self.HttpVideoService.VideoCompress(videoUrl, VideoDir)
	result.CompressUrl = compressUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 44, result) //44视频压缩失败
		self.JsonResponse(w, 405, "视频压缩失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 4, result) //4视频已压缩
	dfsVideo, err := self.HttpVideoService.UploadVideoToDFS(compressUrl, compressUrl)
	result.VideoUrl = dfsVideo.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 55, result) //55压缩视频上传dfs失败
		self.JsonResponse(w, 406, "视频上传失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 5, result) //5压缩视频已上传dfs
	response := handler.ParseResponse(200, "视频压缩成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	//w.Write(jsonData)
	io.WriteString(w, string(jsonData))
}

/**
 * @Author ChenLin
 * @Description //TODO 上传视频获取视频的第一帧图片,http长时间等待
 * @Date 10:31 2022/11/11
 **/

func (self *HttpVideoServer) getPictureOfVideoByUrl(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	w.Header().Set("Content-Type", "application/son")
	log.Println("pasteForm", req.PostForm, req.Form)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	url := req.Form["url"]
	result := handler.VideoProcess{}
	if len(url) < 1 {
		self.JsonResponse(w, 401, "url参数未传递", result)
		return
	}
	videoUrl, err := self.HttpVideoService.DownloadVideo(url[0], VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil || videoUrl == "" {
		log.Println(err)
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	response := handler.ParseResponse(200, "视频截图成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		//go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	//go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	w.Write(jsonData)
}

/**
 * @Author ChenLin
 * @Description //TODO 上传视频获取视频的第一帧图片,http长时间等待
 * @Date 10:31 2022/11/11
 **/

func (self *HttpVideoServer) getPictureOfVideoByFile(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	file, _, err := req.FormFile("video")
	defer file.Close()
	if err != nil {
		self.JsonResponse(w, 400, "文件传输失败", result)
		return
	}
	videoUrl, err := self.HttpVideoService.DownloadVideoByFile(file, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	response := handler.ParseResponse(200, "视频截图成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		//go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	//go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	w.Write(jsonData)
}

func (self *HttpVideoServer) getPictureOfVideoByBytes(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	videoUrl, err := self.HttpVideoService.DownloadVideoByBytes(req.Body, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	screenUrl, err := self.HttpVideoService.ScreenShot(videoUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	response := handler.ParseResponse(200, "视频截图成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		//go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	//go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	w.Write(jsonData)
}

/**
 * @Author ChenLin
 * @Description //TODO 添加url上传任务 type=>1只进行视频截图并返回截图结果(适用于url链接) type=>2对视频截图、压缩上传dfs并返回结果(适用于url链接) type=>3对视频截图、压缩更新dfs并返回结果(适用于url链接)
 * @Date 16:29 2022/11/15
 **/

func (self *HttpVideoServer) addTaskDownloadVideoByUrl(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	url := req.Form["url"]
	redirectUrl := req.Form["redirect_url"]
	type_ := req.Form["type"]
	orderId := req.Form["order_id"]
	result := handler.VideoProcess{}
	if len(url) <= 0 && len(redirectUrl) <= 0 && len(type_) <= 0 {
		self.JsonResponse(w, 401, "有参数未传递", result)
		return
	}
	result.Url = url[0]
	result.RedirectUrl = redirectUrl[0]
	atoi, _ := strconv.Atoi(type_[0])
	result.Type = atoi
	if len(orderId) > 0 {
		atoi1, _ := strconv.Atoi(orderId[0])
		result.OrderId = int32(atoi1)
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(0, result) //1视频已下载
	result.TaskId = id
	if err != nil {
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	go self.HttpVideoService.TaskProducer(result)
	self.JsonResponse(w, 200, "任务添加成功", result)
}

/**
 * @Author ChenLin
 * @Description //TODO 添加文件上传任务 type=>1只进行视频截图并返回截图结果(适用于文件上传) type=>2对视频截图、压缩上传dfs并返回结果(适用于文件上传)
 * @Date 11:09 2022/11/18
 **/

func (self *HttpVideoServer) addTaskDownloadVideoByFile(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	file, _, err := req.FormFile("video")
	defer file.Close()
	if err != nil {
		self.JsonResponse(w, 400, "文件传输失败", result)
		return
	}
	redirectUrl := req.Form["redirect_url"]
	type_ := req.Form["type"]
	result.RedirectUrl = redirectUrl[0]
	atoi, _ := strconv.Atoi(type_[0])
	result.Type = atoi
	videoUrl, err := self.HttpVideoService.DownloadVideoByFile(file, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		_, err := self.HttpVideoService.InsertAndSetStatus(11, result) //11视频下载失败
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(0, result) //1视频已下载
	result.TaskId = id
	if err != nil {
		log.Println(err)
		self.JsonResponse(w, 500, "入库失败", result)
		return
	}
	self.HttpVideoService.TaskProducer(result)
	self.JsonResponse(w, 200, "任务添加成功", result)
}

func (self *HttpVideoServer) addTaskDownloadVideoByBytes(w http.ResponseWriter, req *http.Request) {
	result := handler.VideoProcess{}
	videoUrl, err := self.HttpVideoService.DownloadVideoByBytes(req.Body, VideoDir)
	result.DownloadUrl = videoUrl
	if err != nil {
		log.Println(err)
		_, err := self.HttpVideoService.InsertAndSetStatus(11, result) //11视频下载失败
		if err != nil {
			self.JsonResponse(w, 500, "入库失败", result)
			return
		}
		self.JsonResponse(w, 402, "下载视频失败", result)
		return
	}
	id, err := self.HttpVideoService.InsertAndSetStatus(0, result) //1视频已下载
	result.TaskId = id
	if err != nil {
		log.Println(err)
		response := handler.ParseResponse(500, "入库失败", result)
		jsonData, _ := json.Marshal(response)
		w.Write(jsonData)
		return
	}
	self.HttpVideoService.TaskProducer(result)
	self.JsonResponse(w, 200, "任务添加成功", result)
}

func (self *HttpVideoServer) JsonResponse(w http.ResponseWriter, code int, msg string, i interface{}) {
	response := handler.ParseResponse(200, "任务添加成功", i)
	jsonData, _ := json.Marshal(response)
	w.Write(jsonData)
}

func (self *HttpVideoServer) CheckChunk(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	hash := req.Form["hash"][0]
	hashPath := fmt.Sprintf("%s/%s", Upload, hash)
	chunkList := []string{}
	multiUpload := handler.MultiUpload{}
	state := 0
	isExistPath, err := self.HttpVideoService.MultiDownload.PathExists(hashPath)
	if err != nil {
		log.Println("获取hash路径有误：", err)
		self.JsonResponse(w, 400, "获取hash路径有误", chunkList)
		return
	}
	if isExistPath {
		files, err := ioutil.ReadDir(hashPath)
		if err != nil {
			log.Println("文件读取错误", err)
			self.JsonResponse(w, 400, "文件读取错误", chunkList)
		}
		for _, f := range files {
			fileNmae := f.Name()
			chunkList = append(chunkList, fileNmae)
			fileBaseName := strings.Split(fileNmae, ".")[0]
			if fileBaseName == hash {
				state = 1
			}
		}
		multiUpload.State = state
		multiUpload.ChunkList = chunkList
		if state == 1 {
			self.JsonResponse(w, 201, "文件分片已全部上传", chunkList)
			return
		} else {
			self.JsonResponse(w, 202, "文件分片有部分未上传", chunkList)
			return
		}
	} else {
		multiUpload.State = state
		multiUpload.ChunkList = chunkList
		self.JsonResponse(w, 200, "服务器不存在该文件", chunkList)
		return
	}
}

func (self *HttpVideoServer) MergeChunk(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	hash := req.Form["hash"][0]
	result := handler.VideoProcess{}
	id, err := self.HttpVideoService.InsertAndSetStatus(0, result) //1视频已下载
	hashPath := fmt.Sprintf("%s/%s", Upload, hash)
	isExistPath, err := self.HttpVideoService.MultiDownload.PathExists(hashPath)
	if err != nil {
		log.Println("获取hash路径文件错误:", err)
		go self.HttpVideoService.UpdateProcess(id, 11, result) //11视频下載失败
		self.JsonResponse(w, 400, "获取hash路径文件错误", result)
		return
	}
	if !isExistPath {
		//文件夹不存在
		log.Println("文件目录不存在")
		go self.HttpVideoService.UpdateProcess(id, 11, result) //11视频下載失败
		self.JsonResponse(w, 400, "文件目录不存在", result)
		return
	}
	fileUrl := hashPath + "/" + hash + ".mp4"
	isExistsFile, err := self.HttpVideoService.MultiDownload.PathExists(fileUrl)
	var files []fs.FileInfo
	var create *os.File
	if isExistsFile {
		goto process
	}
	files, err = ioutil.ReadDir(hashPath)
	if err != nil {
		log.Println("合并文件读取失败", err)
		self.JsonResponse(w, 400, "合并文件读取失败", result)
		return
	}
	sort.Slice(files, func(i, j int) bool {
		n1, _ := strconv.Atoi(files[i].Name())
		n2, _ := strconv.Atoi(files[j].Name())
		if n1 > n2 {
			return true
		}
		return false
	})
	create, err = os.Create(fileUrl)
	defer create.Close()
	if err != nil {
		log.Println("创建文件失败", err)
		self.JsonResponse(w, 400, "创建文件失败", result)
		return
	}
	for _, f := range files {
		fileBuffer, err := ioutil.ReadFile(hashPath + "/" + f.Name())
		if err != nil {
			log.Println(hashPath+"/"+f.Name(), "文件打开错误:", err)
			self.JsonResponse(w, 400, "文件打开错误", result)
		}
		if _, err = create.Write(fileBuffer); err != nil {
			log.Println(hashPath+"/"+f.Name(), "文件写入错误:", err)
			self.JsonResponse(w, 400, "文件写入错误", result)
		}
	}
	//文件写入成功后开始进行其他上传和压缩的工作
process:
	screenUrl, err := self.HttpVideoService.ScreenShot(fileUrl, ImageDir)
	result.ScreenUrl = screenUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 22, result) //22视频截图失败
		self.JsonResponse(w, 403, "视频截图失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 2, result) //2视频已截图
	dfsImage, err := self.HttpVideoService.UploadImageToDFS(screenUrl, screenUrl)
	result.ImageUrl = dfsImage.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 33, result) //33视频截图上传dfs失败
		self.JsonResponse(w, 404, "截图上传DFS失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 3, result) //3视频截图已上传dfs
	compressUrl, err := self.HttpVideoService.VideoCompress(fileUrl, VideoDir)
	result.CompressUrl = compressUrl
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 44, result) //44视频压缩失败
		self.JsonResponse(w, 405, "视频压缩失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 4, result) //4视频已压缩
	dfsVideo, err := self.HttpVideoService.UploadVideoToDFS(compressUrl, compressUrl)
	result.VideoUrl = dfsVideo.Message
	if err != nil {
		log.Println(err)
		go self.HttpVideoService.UpdateProcess(id, 55, result) //55压缩视频上传dfs失败
		self.JsonResponse(w, 406, "视频上传失败", result)
		return
	}
	go self.HttpVideoService.UpdateProcess(id, 5, result) //5压缩视频已上传dfs
	response := handler.ParseResponse(200, "视频压缩成功", result)
	err = handler.RemoveFile(response)
	if err != nil {
		go self.HttpVideoService.UpdateProcess(id, 66, result) //66文件删除失败
		log.Println("文件删除失败")
	}
	go self.HttpVideoService.UpdateProcess(id, 8, result) //6文件已删除
	jsonData, _ := json.Marshal(response)
	//w.Write(jsonData)
	io.WriteString(w, string(jsonData))
}

func (self *HttpVideoServer) UploadChunk(w http.ResponseWriter, req *http.Request) {
	req.ParseMultipartForm(32 << 20)
	for key, value := range req.Form {
		fmt.Println("key:", key, " => value :", value)
	}
	hash := req.Form["hash"][0]
	index := req.Form["index"][0]
	file, _, err := req.FormFile("video")
	if err != nil {
		log.Println("获取video文件失败", err)
		self.JsonResponse(w, 400, "获取video文件失败", index)
		return
	}
	hashPath := fmt.Sprintf("%s/%s", Upload, hash)
	isExistPath, err := self.HttpVideoService.MultiDownload.PathExists(hashPath)
	if err != nil {
		log.Println("获取hash文件路径错误", err)
		self.JsonResponse(w, 400, "获取hash文件路径错误", index)
		return
	}
	if !isExistPath {
		if err = os.Mkdir(hashPath, os.ModePerm); err != nil {
			log.Println("创建文件夹失败", err)
			self.JsonResponse(w, 400, "创建文件夹失败", index)
			return
		}
	}
	fileName := fmt.Sprintf("%s/%s", hashPath, index)
	create, err := os.Create(fileName)
	if err != nil {
		log.Println("文件创建失败", err)
		self.JsonResponse(w, 400, "文件创建失败", index)
		return
	}
	if _, err = io.Copy(create, file); err != nil {
		log.Println("文件写入失败", err)
		self.JsonResponse(w, 400, "文件写入失败", index)
		return
	}
	self.JsonResponse(w, 200, "文件分片上传成功", index)
	return
}
